package com.fly.autogetcode;

/**
 * Created by weifeiyang on 2016/7/29 0029.
 */

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * 短信监听
 *
 * @author
 */
public class SMSBroadcastReceiver extends BroadcastReceiver {

    private static MessageListener mMessageListener;
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";//只要注册声明权限即可收到、阻断

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");//获得短信数据
            String format = intent.getStringExtra("format");//短信的类型, GSM与CDMA短信的解码方式不同

            if (null != pdus) {
                for (Object pdu : pdus) {
                    Log.e("pdu", "format" + format);
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu, format);
                    //发送号码-可以过滤需要读取的短信的发送号码
                    String sender = smsMessage.getDisplayOriginatingAddress();
                    //短信内容
                    String content = smsMessage.getDisplayMessageBody();
                    mMessageListener.onReceived(content);
                    abortBroadcast();//中断广播的继续传递,防止优先级低的获取到
                }
            }

        }

    }

    //回调接口
    public interface MessageListener {
        public void onReceived(String message);
    }

    public void setOnReceivedMessageListener(MessageListener messageListener) {
        this.mMessageListener = messageListener;
    }
}